/*
 * Created on Oct 9, 2009
 */
package com.mgmaps.app;

import java.io.IOException;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import com.nutiteq.components.MapPos;
import com.nutiteq.components.WgsPoint;

public class GPSPlace {
  
  private final Image icon;
  private final int iw;
  private final int ih;
  
  private WgsPoint wgs;
  private MapPos mp;
  private MapPos cmp;

  public GPSPlace() throws IOException {
    updateMapPos();
    icon = Image.createImage("/img/gpsdot.png");
    iw = icon.getWidth();
    ih = icon.getHeight();
  }

  /**
   * Getter for wgs.
   *
   * @return Returns the value of wgs.
   */
  public WgsPoint getWgs() {
    return wgs;
  }

  /**
   * Sets the value of wgs.
   *
   * @param wgs The wgs to set.
   */
  public void setWgs(WgsPoint wgs) {
    this.wgs = wgs;
    updateMapPos();
  }
  
  /**
   * Update cached map position for the GPS icon and map center. Should be called
   * whenever the map is moved or zoomed, in order to avoid calling it in every paint().
   */
  public void updateMapPos() {
    if (wgs != null)
      mp = APPCanvas.instance.getMap().getMapPosition(wgs);
    else
      mp = null;
    cmp = APPCanvas.instance.getMap().getInternalMiddlePoint();
  }
  
  /**
   * Paint this place with the virtual radar stuff.
   * @param g Graphics object
   */
  public void paint(Graphics g, int w, int h) {
    // get map x and y
    int x = mp.getX()-cmp.getX()+w/2;
    int y = mp.getY()-cmp.getY()+h/2;
    
    // nothing to paint if outside of screen
    if (x < 0 || y < 0 || x >= w || y >= h)
      return;
    
    // paint icon
    g.drawImage(icon, x-iw/2, y-ih/2, Graphics.TOP|Graphics.LEFT);
  }
}
